package com.ruoyi.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;


@RestController
@RequestMapping("/system/user")
public class SysUserController extends  BaseController {
    @Autowired
    ISysUserService iSysUserService;
    @Autowired
    ISysPostService iSysPostService;
    @Autowired
    ISysRoleService iSysRoleService;
    @Autowired
    SysUserPostService sysUserPostService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    TokenService tokenService;
    @GetMapping("/list")
    public TableDataInfo list(SysUser user){
        startPage();
        List<SysUser> sysUsers = iSysUserService.selectUserList(user);
        TableDataInfo tableDataInfo=new TableDataInfo();
        tableDataInfo.setRows(sysUsers);
        tableDataInfo.setTotal(new PageInfo(sysUsers).getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询");
        return tableDataInfo;
    }
    @GetMapping(value = { "/", "/{userId}"})
    public AjaxResult  PostandRole(@PathVariable(value = "userId", required = false) Long userId){
       AjaxResult ajaxResult= AjaxResult.success();
      List<SysPost> sysPosts = iSysPostService.postAll();
        List<SysRole> sysRoles = iSysRoleService.roleAll();
        ajaxResult.put("posts",sysPosts);
        ajaxResult.put("roles",sysRoles);
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = iSysUserService.selectUserById(userId);
            ajaxResult.put(AjaxResult.DATA_TAG, sysUser);
            ajaxResult.put("postIds", iSysPostService.selectPostListByUserId(userId));
            ajaxResult.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
      return ajaxResult;
  }

  @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser sysUser, SysUserPost sysUserPost,SysUserRole sysUserRole){
            if (UserConstants.NOT_UNIQUE.equals(iSysUserService.checkUserNameUnique(sysUser.getUserName()))){
                return AjaxResult.error("用户名"+sysUser.getUserName()+"重复");
            }
            else if (StringUtils.isNotEmpty(iSysUserService.checkPhoneUnique(sysUser))&& UserConstants.NOT_UNIQUE.equals(iSysUserService.checkPhoneUnique(sysUser))
            ){
                return AjaxResult.error("电话号码"+sysUser.getPhonenumber()+"重复");
            }else if (StringUtils.isNotEmpty(iSysUserService.checkEmailUnique(sysUser))&&UserConstants.NOT_UNIQUE.equals(iSysUserService.checkEmailUnique(sysUser))){
                return  AjaxResult.error("邮箱"+sysUser.getEmail()+"重复");
            }
      sysUser.setCreateBy(getUsername());
      sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
      iSysUserService.insertUser(sysUser);
      for (Long postId : sysUser.getPostIds()) {
          sysUserPostService.delUserandPost(sysUser.getUserId());
          sysUserPost.setUserId(sysUser.getUserId());
          sysUserPost.setPostId(postId);
      }
      sysUserPostService.inseUserandPost(sysUserPost);

      return toAjax(1);
  }

  @PutMapping
    public  AjaxResult update(@Validated @RequestBody SysUser sysUser,SysUserPost sysUserPost){
      for (Long postId : sysUser.getPostIds()) {
          sysUserPostService.delUserandPost(sysUser.getUserId());
          sysUserPost.setUserId(sysUser.getUserId());
          sysUserPost.setPostId(postId);
      }
      sysUserPostService.inseUserandPost(sysUserPost);

      sysUser.setUpdateBy(getUsername());
   return toAjax(iSysUserService.updateUser(sysUser));
  }

  @DeleteMapping("/{userId}")
    public  AjaxResult delete(@PathVariable Long[] userId){
      return toAjax(iSysUserService.deleteUserByIds(userId));
  }


  @PutMapping("/resetPwd")
    public  AjaxResult profile( @RequestBody SysUser sysUser){
      sysUser.setUpdateBy(getUsername());
      sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
       return toAjax(iSysUserService.resetPwd(sysUser));
  }

    @GetMapping("/authRole/{userId}")
    public AjaxResult role(@PathVariable  Long userId){
        AjaxResult ajax = AjaxResult.success();
        SysUser user = iSysUserService.selectUserById(userId);
        List<SysRole> roles = iSysRoleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", roles);
        return ajax;
    }

    @PutMapping("/authRole")
    public AjaxResult authRole(SysUserRole sysUserRole, Long userId, Long[] roleIds){
              iSysUserService.insertUserAuth(userId,roleIds);
        return success();
    }

    @PutMapping("/changeStatus")
    public  AjaxResult changeStatus( @RequestBody SysUser sysUser){
        sysUser.setUpdateBy(getUsername());
        return toAjax(iSysUserService.updateUserStatus(sysUser));
    }

    @GetMapping("/profile")
    public  AjaxResult profile(){
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", iSysRoleService.roleAllandUsername(loginUser.getUsername()));
        ajax.put("postGroup", iSysPostService.postAllandUsername(loginUser.getUsername()));
        return ajax;
    }
    @PutMapping("/profile")
    public AjaxResult profil(@RequestBody SysUser user){
        LoginUser loginUser=getLoginUser();
        SysUser sysUser=loginUser.getUser();
        user.setUserName(user.getUserName());
        sysUser.setUserId(user.getUserId());
        if (iSysUserService.updateUser(user)>0){
            sysUser.setPhonenumber(user.getPhonenumber());
            sysUser.setNickName(user.getNickName());
            sysUser.setEmail(user.getEmail());
            sysUser.setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return null;

    }



}
